<template>
  <div class="login">
    <div class="loginContainer">
      <div class="logo">
        <svg-icon
          icon-name="cbi:deezer-logo"
          custom-class="text-#ea7f11 text-[28px]"
        ></svg-icon>
        <h1>YM-Admin</h1>
      </div>
      <el-form
        :rules="loginRules"
        :model="loginForm"
        ref="loginRef"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password"></el-input>
        </el-form-item>

        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { login } from "@/api/login"
import { useAuthStore } from "@/store/auth"
import type { FormInstance } from "element-plus"

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const loginRef = ref<FormInstance>()
const loginState = reactive({
  loginForm: {
    username: "",
    password: ""
  },
  loginRules: {
    username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
    password: [{ required: true, trigger: "blur", message: "请输入密码" }]
  }
})

const { loginForm, loginRules } = loginState
const { proxy } = getCurrentInstance()!

const handleLogin = () => {
  loginRef.value?.validate(async (valid) => {
    if (valid) {
      const loginResponse = await login(loginForm).catch((err) => {
        if (err.response.status === 401) {
          proxy?.$message({
            message: err.response.data.message,
            type: "error",
            showClose: true
          })
        }
      })

      authStore.setToken(loginResponse.data.token)
      router.push({
        path: (route.query.redirect as string) || "/"
      })
    }
  })
}
</script>

<style scoped lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  .loginContainer {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px #ccc;
    .logo {
      display: flex;
      align-items: center;
      h1 {
        margin-left: 8px;
      }
    }
    .el-form {
      display: flex;
      flex-direction: column;
      width: 400px;
      padding: 20px;

      .el-form-item {
        width: 100%;
      }

      .el-button {
        margin-top: 10px;

        &:active {
          border-color: rgb(245, 191, 136);
          background-color: rgb(245, 191, 136);
        }
      }
    }
  }
}
</style>
